package club.cearnach.api;

import club.cearnach.api.service.IVisitorService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 初始化redis在线人数以及同步总访问人数
 *
 * @author 阮胜
 * @date 2018/5/16 10:48
 */
@Configuration
public class InitVisitorParamOnStartup implements ApplicationListener<ContextRefreshedEvent> {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    private final IVisitorService visitorService;
    private final StringRedisTemplate stringRedisTemplate;

    public InitVisitorParamOnStartup(IVisitorService visitorService, StringRedisTemplate stringRedisTemplate) {
        this.visitorService = visitorService;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        initVisitorParam();
    }

    private void initVisitorParam() {
        long count = visitorService.count();
        stringRedisTemplate.opsForValue().set("totalVisitors", String.valueOf(count));
        stringRedisTemplate.opsForValue().set("onlineVisitors", "0");
    }
}